<template>
  <div class="player_div">
    <!--页面头部 -->
    <div class="player_header">
      <span style="margin-left: 40px;">{{title}}(在线人数：{{online}})</span>
      <button @click="close" style="padding: 10px 20px; background-color: red; color: white; border: 0px; border-radius: 5px; margin-right: 40px;">退出课堂</button>
    </div>
    <!-- 直播页面 -->
    <div class="player_media_div">
      <div class="player_video">
        <video ref="remotevideo" autoplay controls></video>
      </div>
      <div class="player_action">
 <!--       <div style="flex: 1;display: flex; flex-direction: column; justify-content: start;">
          <div style="margin-top: 40px; color: white;">在线人数：{{online}}</div>
          <div style="margin-top: 40px; color: white;">
            <select v-model="media.privier" style="padding: 10px 20px;">
              <option value="0">清晰度优先</option>
              <option value="1">流畅度优先</option>
            </select>
          </div>
          <div style="margin-top: 40px;">
            <button @click="started" style="padding: 10px 20px; background-color: #409EFF; color: white; border: 0px; border-radius: 5px; box-shadow: 5px 5px 5px #000000;">开始上课</button>
          </div>
          <div style="margin-top: 40px;">
            <button @click="close" style="padding: 10px 20px; background-color: red; color: white; border: 0px; border-radius: 5px; box-shadow: 5px 5px 5px #000000;">结束上课</button>
          </div>
        </div> -->

        <div style="width: 100%; height: 250px; background-color: white; text-align: left;" ref="msgDiv">
        </div>
        <div style="margin-top: 10px; margin-bottom: 10px;">
          <input style="width: 60%;margin-right: 10px;"/><button>发送</button>
        </div>
      </div>
    </div>
  </div>
</template>


<script>
  import kurentoUtils from 'kurento-utils'

  export default {
    data(){
      return {
        cid: this.$route.params.cid,//课程id
        token: this.$route.params.token,//微信用户令牌
        uid: "",//用户id
        title: "课程标题",//标题
        descId: 0,//课程章节id
        online: 0,//在线人数
        media: {
          privier: 0,//优先级类型
          webRtcPeer: null
        },
        websocket: {
          ws: null,
          url: "ws://192.168.0.110:9300/"
        }
      }
    },
    methods: {
      //websocket初始化连接
      wsConn(){
        this.websocket.ws = new WebSocket(this.websocket.url);
        this.websocket.ws.onopen = this.onopen;
        this.websocket.ws.onclose = this.onclose;
        this.websocket.ws.onerror = this.onerror;
        this.websocket.ws.onmessage = this.onmessage;
      },
      onopen(){
        console.log("服务器连接成功....");
        this.showInfo("系统", "成功连接聊天服务器....", "grad");

        //请求课程信息
        var msg = {
          id: "conn",
          role: "slave",
          token: this.token,
          cid: this.cid
        }
        this.sendWsMsg(msg);
      },
      onclose(){
        console.log("断开了连接....");
        this.showInfo("系统", "断开了服务器连接....", "grad");
        this.websocket.ws = null;
      },
      onerror(e) {
        console.log("服务器连接异常...");
        this.showInfo("系统", "聊天服务器连接失败....", "grad");
        this.websocket.ws = null;
      },
      //接收到服务器的消息
      onmessage(msg) {
        var obj = JSON.parse(msg.data);
        console.log("[reciver msg] 接收到服务器的消息", obj);
        var id = obj.id;
        var content = obj.content;
        switch (id) {
          //初始化连接返回结果
          case "connResult":
            this.title = content.title;
            this.descId = content.descId;
            this.uid = content.uid;

            if(content.isPlayer){
              //自动连接媒体服务器
              this.initRemoteMedia();
            } else {
              this.$message.warning("直播还未开始....");
            }
            break;
          //直播方媒体流上线
          case "masterOnline":
            //自动连接媒体服务器
            this.initRemoteMedia();
            break;
          //在线人数更新
          case "onlineResult":
            this.online = content;
            break;
          //Kurento服务器的SDP应答
          case "answerResult":
            this.media.webRtcPeer.processAnswer(content);
            break;
          //ice候选者信息
          case "iceCandidate":
            this.media.webRtcPeer.addIceCandidate(JSON.parse(content));
            break;
          case "tokenError":
            this.websocket.ws.close();
            this.websocket.ws = null;
            alert("登录凭证过期，请重新登录后再开始上课！");
            break;
          case "masterClose":
            if (this.media.webRtcPeer) {
            	this.media.webRtcPeer.dispose();
            	this.media.webRtcPeer = null;
            }
            break;
        }
      },
      //初始化本地媒体
      async initRemoteMedia(){

        //准备相关参数
        var option = {
          //本地的video标签对象
          remoteVideo: this.$refs.remotevideo,
          //ice候选者的回调方法
          onicecandidate: this.onIceCandidate,
          //stun服务器地址
          configuration: {
            iceServers: [
              {
                urls: "stun:120.78.159.145:3478"
              },{
                urls: "turn:120.78.159.145:3478",
                username: "kurento",
                credential: "kurento"
              }
            ]
          }
        };

        //创建kurento的RTC连接, 直播方
        this.media.webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly(option, (error) => {
            //回调方法
            if(error) {
              //存在异常
              return console.error(error);
            }

            //成功，创建提案
            this.media.webRtcPeer.generateOffer(this.onOfferViewer);
        });
      },
      //创建提案的方法
      onOfferViewer(error, offerSdp){
        if(error){
          //提案创建有问题
          return console.error(error);
        }

        //提案创建成功，将提案发送给WebSocket服务器
        var msg = {
          id: "slaveOffer",
          cid: this.cid,
          uid: this.uid,
          content: offerSdp
        };
        this.sendWsMsg(msg);
      },
      //ice的回调方法
      onIceCandidate(ice){
        console.log("ice候选者：", ice);

        //远程发送给websocket对象，将ice候选者
        var msg = {
          id: "onIceCandidate",
          content: ice
        };
        this.sendWsMsg(msg);
      },
      //关闭直播
      close(){
        //关闭直播
        if (this.media.webRtcPeer) {
        	this.media.webRtcPeer.dispose();
        	this.media.webRtcPeer = null;
        }

        //发送消息给服务器
        var msg = {
          id: "slaveClose",
          cid: this.cid,
          uid: this.uid
        };
        this.sendWsMsg(msg);

        //调用小程序的退出
        wx.miniProgram.navigateBack();
      },
      //现在信息到聊天框
      showInfo(source, content, color){
        var dcolor = "black";
        if(color) {
          dcolor = color;
        }
        var con = "<div style='color: " + dcolor + "'>[" + source + "]:" + content + "</div>";
        this.$refs.msgDiv.innerHTML += con;
      },
      //发送WebSocket消息
      sendWsMsg(obj){
        if(this.websocket.ws){
          if(typeof(obj) != "string"){
            obj = JSON.stringify(obj);
          }
          console.log("[send msg] 发送消息给服务器！", obj);
          this.websocket.ws.send(obj);
        } else {
          console.log("[error] 服务器还未连接...");
        }
      }
    },
    mounted() {
      //页面加载时触发
      //连接websocket
      this.wsConn();
    }
  }
</script>

<style>
  body {
    padding: 0px;
    margin: 0px;
  }

  .player_div {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .player_header {
    background-color: black;
    width: 100%;
    height: 60px;
    min-height: 60px;
    color: white;
    text-align: left;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .player_media_div {
    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .player_video {
    height: 100%;
    width: 100%;
    background-color: #000000;
  }

  .player_video video {
    height: 100%;
    width: 100%;
    max-width: 900px;
    max-height: 100%;
  }

  .player_action {
    background-color: gray;
    height: 100%;
    flex: 1;
    display: flex;
    flex-direction: column;
  }
</style>
